﻿//粘贴world
puxu.EdPuXu.prototype.pasteWord = function (html) {
	//是否是word过来的内容
	function isWordContent(str) {
		return /(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<(v|o):|lang=)/gi.test(str);
	}
	//转换cm/pt单位到px
	function unitToPx(v) {
		if (!/(pt|cm)/.test(v)) return v;
		var unit;
		v.replace(/([\d.]+)(\w+)/, function (str, v, u) { v = v, unit = u; });
		v = unit == 'cm' ? parseFloat(v) * 25 : Math.round(parseFloat(v) * 96 / 72);
		return v + (v ? 'px' : '');
	}
	//去掉小数
	function transUnit(v) {
		return v.replace(/[\d.]+\w+/g,
			function (m) { return unitToPx(m) });
	}
	//处理word格式
	function filterPasteWord(str) {
		return str
			.replace(/<html.*?>/gi, "")
			.replace(/<body.*?>/gi, "")
			.replace(/<!.*?>/gi, '')
			.replace(/<head.*?>.*?<\/head>/gi, '')
			.replace(/<\/body>/gi, '')
			.replace(/<\/html>/gi, '')
			.replace(/[\t\s]+/gi, ' ')
			.replace(/<xml.*?>.*?<\/xml>/gi, '')
			.replace(/<o:p>.*?<\/o:p>/gi, '')
			.replace(/<span[^>]*>\s*<\/span>/gi, '')
			.replace(/<(span|font|p|b|i|u|s)[^>]*>\s*<\/\1>/gi, '')
			.replace(/v:\w+=(["']?)[^'"]+\1/g, '')
			.replace(/<p[^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>")
			//去掉多余的属性
			.replace(/\s+(class|lang|align)\s*=\s*(['"]?)([\w-]+)\2/gi, function (str, name, marks, val) {
				//保留list的标示
				return name == "class" && val == "MsoListParagraph" ? str : '';
			})
			//清除多余的font/span不能匹配&nbsp;有可能是空格
			.replace(/<(font|span)[^>]*>(\s*)<\/\1>/gi, function (a, b, c) {
				return c.replace(/[\t\r\n ]+/g, ' ');
			})
			//处理style的问题
			.replace(/(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi, function (str, tag, tmp, style) {
				var n = [], s = style.replace(/^\s+|\s+$/, "").replace(/&#39;/g, "'").replace(/&quot;/gi, "'").replace(/[\d.]+(cm|pt)/g, function (str) {
					return unitToPx(str);
				}).split(/;\s*/g);
				for (var i = 0, v; v = s[i]; i++) {
					var name, value, parts = v.split(":");
					if (parts.length == 2) {
						name = parts[0].toLowerCase().trim(), value = parts[1].toLowerCase().trim();
						if ((/^(background)\w*/.test(name) && value.replace(/(initial|\s)/g, "").length == 0) || (/^(margin)\w*/.test(name) && /^0\w+$/.test(value))) continue;
						switch (name) {
							case "mso-vertical-align-alt":
								if (!/<table/.test(tag)) n[i] = name.replace(/^mso-|-alt$/g, "") + ":" + transUnit(value);
								continue;
							case "horiz-align":
								n[i] = "text-align:" + value;
								continue;
							case "vert-align":
								n[i] = "vertical-align:" + value;
								continue;
							case "mso-foreground":
								n[i] = "color:" + value;
								continue;
							case "mso-highlight":
								n[i] = "background:" + value;
								continue;
							case "mso-default-height":
								n[i] = "min-height:" + transUnit(value);
								continue;
							case "mso-default-width":
								n[i] = "min-width:" + transUnit(value);
								continue;
							case "mso-padding-between-alt":
								n[i] = "border-collapse:separate;border-spacing:" + transUnit(value);
								continue;
							case "text-line-through":
								if (value == "single" || value == "double") n[i] = "text-decoration:line-through";
								continue;
							case "mso-zero-height":
								if (value == "yes") n[i] = "display:none";
								continue;
							case "margin":
								if (!/[1-9]/.test(value)) continue;
						}
						if (/^(mso|column|font-emph|lang|layout|line-break|list-image|nav|panose|punct|row|ruby|sep|size|src|tab-|table-border|text-(?:decor|trans)|top-bar|version|vnd|word-break)/.test(name) || (/text\-indent|padding|margin/.test(name) && /\-[\d.]+/.test(value))) continue;
						n[i] = name + ':' + parts[1];
					}
				}
				return (tag + (n.length ? ' style="' + n.join(";").replace(/;{2,}/g, ";") + '"' : ""));
			})
	}
	return isWordContent(html) ? filterPasteWord(html) : html;
};


//粘贴富文本
puxu.EdPuXu.prototype.pasteHTML = function (html) {

	//过滤粘贴附加的html标签
	html = html.replace(/<html.*?>/g, "")
		.replace(/<body.*?>/g, "")
		.replace(/<!.*?>/g, '')
		.replace(/<head.*?>.*?<\/head>/g, '')
		.replace(/<\/body>/g, '')
		.replace(/<\/html>/g, '')
		.replace(/\s+(id|class|lang|align|data|data-\w*)\s*=\s*(['"]?).*?\2/gi, '');

	//过滤被禁止的html标签
	for (var i = 0; i < this.filterTag.length; i++) {
		html = html.replace(new RegExp("<" + this.filterTag[i] + "[^>]*>.*?<\/" + this.filterTag[i] + ">", "gim"), '');
	}

	//过滤style属性
	var _z = this;
	html = html.replace(/\s+style\s*=\s*(['"]?)(.*?)\1/g, function (a, q, b) {
		if (b) {
			b = b.replace(/(&#39;|&quot;)/gi, "'"); //防止属性中的单双引号被转义，注意转义以后的分号，因为需要通过分号来分割样式
			var info = b.split(';');
			if (info.length) {
				var h = [];
				for (var i = 0; i < info.length; i++) {
					var styleName = info[i].trim();
					if (styleName) {
						var name = styleName.split(':')[0];
						if (!_z.filterStyle.includes(name)) {
							//用来将rgb颜色转为十六进制，rgba不变
							var color = styleName.split(':');
							if (color.length > 1 && /rgb\s*\(/gi.test(color[1])) {
								color[1] = color[1].replace(/rgb\s*\(.*?\)/gi, function (a) {
									a = a.split(/\D+/);
									return "#" + ((1 << 24) + (parseInt(a[1]) << 16) + (parseInt(a[2]) << 8) + parseInt(a[3])).toString(16).slice(1);
								});
								h.push(name + ':' + color[1]);
							} else {
								h.push(styleName);
							}
						}
					}
				}
				return ' style="' + h.join(';') + '"';
			}
		}
		return '';
	});

	//div转p
	return html.replace(/<div([^>]*)>/g, "<p$1>").replace(/<\/div>/g, "</p>");
};



//美化HTML格式
puxu.EdPuXu.prototype.formatHTML = function (html) {
	html = html.replace(/[\t\s]+/g, ' ')

		//清除空标签
		.replace(/<(span|font|p|b|i|u|s)[^>]*>(<(?!img)[^>]*>)*<\/\1>/gi, '')

		//清除标签内末尾的空格，起到美化作用
		.replace(/<(.+)\s+>/g, '<$1>')

		//格式美化
		//.replace(/>\s*<p/g,">\n<p");
		.replace(/(<br\/*>){1,}/gi, '<br/>');

	//格式化块级元素段落
	for (var i = 0; i < this.blockTag.length; i++) {
		html = html.replace(new RegExp("<\/" + this.blockTag[i] + ">", "gim"), "<\/" + this.blockTag[i] + ">\r\n");
	}
	return html.replace(/\r\n{1,}/gim, "\r\n").trim();
}

//纯文本粘贴
puxu.EdPuXu.prototype.paste = function () {
	// 干掉IE http之类地址自动加链接
	try { this.w_left.document.execCommand("AutoUrlDetect", false, false); } catch (e) { }
	var _z = this;
	var _w = this.w_left;

	//上传
	var upload = function (imgBase64) {
		//如果禁用上传到服务器，则直接以base64格式显示图像
		if (!_z.screenshotUpload) {
			var p = _z.c('p');
			var a = _z.c('img');
			a.src = imgBase64;
			p.appendChild(a);
			_z.setHTML(p, true);
			return;
		}
		function dataURItoBlob(base64Data) {
			var byteString;
			if (base64Data.split(',')[0].indexOf('base64') >= 0) {
				byteString = atob(base64Data.split(',')[1]);
			} else {
				byteString = unescape(base64Data.split(',')[1]);
			}
			var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
			var a = new Uint8Array(byteString.length);
			for (var i = 0; i < byteString.length; i++) {
				a[i] = byteString.charCodeAt(i);
			}
			return new Blob([a], { type: mimeString });
		}
		var blob = dataURItoBlob(imgBase64);
		var formData = new FormData();
		formData.append('file[]', blob);
		_z.ajax({
			url: _z.uploadUrl,
			data: formData,
			success: function (res) {
				if (res) {
					for (var f = 0; f < res.length; f++) {
						if (res[f].error) {
							_z.imgUpload.error(res[f], res);
							_z.imgUpload.complete(res[f], res);
							alert(res[f].error);
						} else {
							var p = _z.c('p');
							var a = _z.c('img');
							a.src = res[f].url;
							p.appendChild(a);
							_z.setHTML(p, true);
							_z.imgUpload.success(res[f], res);
							_z.imgUpload.complete(res[f], res);
						}
					}
				} else {
					_z.imgUpload.error(res);
					_z.imgUpload.complete(res);
				}
			},
			error: function (xhr) {
				_z.imgUpload.error(xhr);
				_z.imgUpload.complete(xhr);
			}
		})
	};
	var getBase64 = function () {
		setTimeout(function () {
			//保证图片先插入到div里，然后去获取值
			var imgList = _z.d.body.getElementsByTagName('img');
			for (var i = 0; i < imgList.length; i++) {
				if (imgList[i].src.substr(0, 5) == 'data:') {
					upload(imgList[i].src);
					imgList[i].parentNode.removeChild(imgList[i]);
					break;
				}
			}
		}, 10);
	};

	this.d_left.body.addEventListener('paste', function (e) {
		
		 console.log("11111111111111111111111");
		 console.log(_z.range.getRangeAt(0).startOffset);
		if (!_z.isIE()) e.preventDefault();
		var clip = (window.clipboardData || e.clipboardData || e.originalEvent.clipboardData);
		//获取粘贴板数据
		var text = clip.getData('Text');
		var str = _z.pasteText && text.length ? text : (clip.getData('text/html').length ? clip.getData('text/html') : text);
		var htmlContent = clip.getData('text/html') ? true : false;
		//富文本粘贴模式开启状态下
		if (htmlContent && !_z.pasteText) {
			//复制过来的数据有些情况会被转义，需要再次转义回来，单双引号全部转为单引号比较可靠
			str = str.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&nbsp;/g, " ").replace(/&#39;/g, "'").replace(/&quot;/g, "'");
		}

		//截图粘贴功能 判断是否开启，判断是否在pre标签中
		if (_z.screenshot && !_z.inNodeParent(_z.range.getRangeAt(0).endContainer, 'pre')) {
			if (clip) {
				//ie11没有items
				var blob = clip.items ? (clip.items[0].type.indexOf("image") !== -1 ? clip.items[0].getAsFile() : 0) : 0;
				if (blob) {
					var reader = new FileReader();
					reader.onload = function (e) {
						//图片的Base64编码字符串
						var base64_str = e.target.result;
						upload(base64_str);
					}
					reader.readAsDataURL(blob);
				}
			}
			getBase64();
		}
		if (!str.length) return;
		//源码模式下直接纯文本粘贴
		if (_z.code) {
			_z.setText(text);
			return;
		}

		var t = str.replace(/[\r|\n]+/g, "\n").split("\n");
		//判断光标是否在pre标签中
		if (_z.inNodeParent(_z.range.getRangeAt(0).endContainer, 'pre')) {
			var t = text.replace(/[\r|\n]+/g, "\n").split("\n");
			for (var i = 0; i < t.length; i++) {
				t[i] = _z.toText(t[i]);
			}
			_z.setText(t.join('<br>'), true);
			return;
		}

		if (_z.pasteText && t.length == 1) {
			_z.setText(str);
			return;
		}

		//纯文本粘贴
		if (_z.pasteText || !htmlContent) {
			for (var i = 0; i < t.length; i++) {
				if (t[i]) { //有效去除空标签
					_z.setText('<p>' + t[i].trim() + '<p>', true);
				}
			}
		} else {
			//过滤word
			str = _z.pasteWord(str);
			str = _z.formatHTML(str);
			//过滤HTML
			str = _z.pasteHTML(str);
			//格式化HTML
			str = _z.formatHTML(str);
			_z.setText(str, true);
		}
		//处理冗余标签
		str = _z.getHTML();
		_z.d.body.innerHTML = str;
		str = _z.getHTML();
		str = str.replace(/<p><\/p>/gi, '')
			.replace(/<\/p><br>/gi, '')
			.replace(/<(span|font|p|b|i|u|s)[^>]*>(<(?!img)[^>]*>)*<\/\1>/gi, '');
		_z.d.body.innerHTML = str;

		//下载网络图片到本地
		if (_z.imgAutoUpload) {
			var str = _z.getHTML();
			str.replace(/<img .*?src="(.*?)".*?>/gi, function (all, b = '') {
				//这里必须使用闭包，因为使用了异步
				(function (a) {
					//判断是否为本地图片
					if (b.substr(0, 1) == '/' && b.substr(0, 2) != '//') return;
					//如果为网络图片，过滤白名单域名
					_z.imgDomain = _z.imgDomain && Array.isArray(_z.imgDomain) ? _z.imgDomain : [document.domain];
					//将当前域名加入白名单
					!_z.imgDomain.includes(document.domain) && _z.imgDomain.push(document.domain);
					for (var i = 0; i < _z.imgDomain.length; i++) {
						if (new RegExp("^((http|https):)*(\/)*" + _z.imgDomain[i], "i").test(a)) {
							return;
						}
					}
					_z.ajax({
						url: _z.uploadUrl,
						data: { 'iceEditor-img': a },
						success: function (res) {
							if (res && !res.error) {
								str = str.replace(new RegExp(a, 'gi'), res.url);
								_z.setValue(str);
								_z.imgUpload.success(res);
								_z.imgUpload.complete(res);
							} else {
								_z.imgUpload.error(res, res);
								_z.imgUpload.complete(res, res);
							}
						},
						error: function (xhr) {
							_z.imgUpload.error(xhr);
							_z.imgUpload.complete(xhr);
						}
					})
				})(b);
			});
		}

	});

	function nodePrev(el) {
		if (!el) return false;
		var node = el.nextSibling;
		if (node && node.nodeType != 1) node = nodePrev(node);
		return node;
	}
	this.d_left.body.addEventListener('keydown', function (e) {
		var range = _z.range.getRangeAt(0);
		if (e.keyCode == 13) {
			//回车处理pre中的代码
			if (_z.inNodeParent(range.endContainer, 'pre')) {
				//这一步是真特么费劲
				if (_z.range.anchorNode.parentNode.tagName == 'PRE') {
					_z.element.focus();
					//判断一下光标是否处于当前节点文字的末尾
					var isCursorEnd = range.endContainer.length == range.startOffset;
					//Chrome浏览器有个非常操蛋的毛病，就是如果当前节点是最后一个,输入文字后回车
					//第一次换行不起作用，需要两次回车才能换行
					//所以需要判断当前节点是否为最后一个节点，完全是给Chrome用的
					var isNodeEnd = nodePrev(range.endContainer) ? false : true;
					var br = isNodeEnd ? '<br><br>' : '<br>';
					var range = _z.range.getRangeAt(0);
					range.insertNode(range.createContextualFragment(br));
					//接下来这一步是为了修正光标位置
					var node = _z.range.anchorNode.nextSibling.nextSibling;
					range.setStart(node, 0);
					range.setEnd(node, 0);
					range.collapse();
				} else if (_z.parentTagName == 'PRE' || _z.range.anchorNode.tagName == 'PRE') {
					_z.setText('<br>', true);
				}
				e.preventDefault();
				return;
			}
		}
		// 去除Crtl+b/Ctrl+i/Ctrl+u等快捷键
		// e.metaKey for mac
		if (e.ctrlKey || e.metaKey) {
			switch (e.keyCode) {
				case 13: { e.preventDefault(); break; }
				case 66: //ctrl+B or ctrl+b
				case 98:
				case 73: //ctrl+I or ctrl+i
				case 105:
				case 85: //ctrl+U or ctrl+u
				case 117: { e.preventDefault(); break; }
			}
		}
	});
};